package service

import (
	"sync"

	"github.com/cloudwego/eino/schema"
)

// Message 轻量级的消息结构体
type Message struct {
	Role    string // 消息角色（user/assistant）
	Content string // 消息内容
}

// ConversationManager 用于管理会话历史的结构体
type ConversationManager struct {
	mutex     sync.RWMutex
	histories map[string][]Message
}

// 全局的会话历史管理器实例
var conversationManager *ConversationManager

// InitConversationManager 初始化会话历史管理器
func InitConversationManager() {
	conversationManager = &ConversationManager{
		histories: make(map[string][]Message),
	}
}

// AddMessage 添加消息到会话历史
func (cm *ConversationManager) AddMessage(conversationId string, role string, content string) {
	cm.mutex.Lock()
	defer cm.mutex.Unlock()

	msg := Message{
		Role:    role,
		Content: content,
	}

	cm.histories[conversationId] = append(cm.histories[conversationId], msg)
}

// GetHistory 获取指定会话的历史记录
func (cm *ConversationManager) GetHistory(conversationId string) []Message {
	cm.mutex.RLock()
	defer cm.mutex.RUnlock()

	return cm.histories[conversationId]
}

// ToSchemaMessages 将历史记录转换为schema.Message数组
func (cm *ConversationManager) ToSchemaMessages(conversationId string) []*schema.Message {
	history := cm.GetHistory(conversationId)
	messages := make([]*schema.Message, 0, len(history))

	for _, msg := range history {
		var schemaMsg *schema.Message
		switch msg.Role {
		case "user":
			schemaMsg = schema.UserMessage(msg.Content)
		case "assistant":
			schemaMsg = schema.AssistantMessage(msg.Content, nil)
		}
		if schemaMsg != nil {
			messages = append(messages, schemaMsg)
		}
	}

	return messages
}

// GetConversationManager 获取会话管理器实例
func GetConversationManager() *ConversationManager {
	if conversationManager == nil {
		InitConversationManager()
	}
	return conversationManager
}
